package com.sweet.fourtimeoa.aspect;

import com.sweet.fourtimeoa.interceptor.LogInterceptor;
import com.sweet.fourtimeoa.mapper.SystemMapper;
import com.sweet.fourtimeoa.pojo.entity.OperationLogs;
import com.sweet.fourtimeoa.util.BaseContext;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;

import java.lang.reflect.Method;
import java.util.Date;

import static com.github.pagehelper.util.MetaObjectUtil.method;

@Aspect
@Component
public class LogAspect {
    @Autowired
    private SystemMapper systemMapper;
    @Pointcut("execution(* com.sweet.fourtimeoa.controller.*.*(..))")
    public void log(){}
    @AfterReturning("log()")
    public void before(JoinPoint joinPoint){

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Operation operation = method.getAnnotation(Operation.class);
        String description = operation.summary();
        OperationLogs logs = new OperationLogs();

        if (BaseContext.getCurrentId() != null ){
            logs.setUserId(BaseContext.getCurrentId().intValue());
        }else {
            logs.setUserId(1);
        }
        logs.setAction(description);
        logs.setObject(methodSignature.getDeclaringTypeName());
        logs.setDescription(description);
        logs.setCreatedAt(new Date());
        systemMapper.addLog(logs);
    }
}
